<template>
  <el-form
    ref="loginFormRef"
    class="login_phone"
    :model="loginForm"
    :rules="loginRules"
    size="default"
  >
    <el-form-item prop="phone">
      <el-input
        v-model="loginForm.phone"
        placeholder="手机号"
        class="login_input"
      >
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input
        v-model="loginForm.code"
        class="login_input"
        placeholder="短信验证码"
      >
        <template #suffix>
          <el-button
            class="send_code"
            type="text"
            round
            size="small"
            :disabled="loginForm.disabled || loginForm.time > 0"
            @click.stop="getCode(loginFormRef)"
            >{{
              loginForm.disabled || loginForm.time > 0
                ? loginForm.second + 'S'
                : '发送验证码'
            }}</el-button
          >
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <!-- <el-button :icon="CircleClose" round @click="resetForm(loginFormRef)" size="default">重置</el-button> -->
  <el-button
    class="login-btn"
    size="default"
    type="primary"
    :loading="loading"
    @click="login(loginFormRef)"
  >
    登录
  </el-button>
</template>

<script setup lang="ts">
import { ref, unref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElForm, ElMessage } from 'element-plus';
import { loginApi } from '@/api/api.js';
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;
// 定义 formRef校验规则
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginForm = reactive({
  second: 60,
  phone: '',
  code: '',
  disabled: false,
  time: 0,
  sendAuthCode: true,
});

const telValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号'));
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error('手机号格式不正确'));
  } else {
    callback();
  }
};
const loginRules = reactive({
  phone: [{ validator: telValidator, trigger: 'blur', required: true }],
  code: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
});
const loading = ref<boolean>(false);
const router = useRouter();
// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;
    $request(loginApi.loginByPhone, {
      phone: loginForm.phone,
      code: loginForm.code,
    })
      .then(() => {
        router.push({
          path: '/',
        });
      })
      .catch(() => {
        loading.value = false;
      });
  });
};

const getCode = () => {
  const formRef = unref(loginFormRef);
  formRef.validateField('phone', (valid: boolean) => {
    if (!valid) return;
    // 验证通过
    let timer = setInterval(() => {
      if (loginForm.second > 0) {
        loginForm.sendAuthCode = true; // 是否禁用点击事件
        loginForm.second--; // 倒计时
      } else {
        loginForm.sendAuthCode = false;
        loginForm.second = 60;
        clearInterval(timer);
      }
    }, 1000);
    // 发送验证码接口
    handleSendCode();
  });
};
const handleSendCode = () => {
  $request(loginApi.sendLoginPhoneCode, {
    phone: loginForm.phone,
  }).then(() => {
    ElMessage({
      duration: 2.5 * 1000,
      message: '登录验证码短信已发送，请及时查收',
      //message: `${res.msg}`,
      type: 'success',
    });
  });
};

onMounted(() => {
  // 监听enter事件（调用登录）
  document.onkeydown = (e: any) => {
    e = window.event || e;
    if (e.code === 'Enter' || e.code === 'enter' || e.code === 'NumpadEnter') {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
.login_phone {
  $cursor: gray;
  .login_input {
    height: 46px;
    input {
      -webkit-appearance: none;
      padding: 12px 5px 12px 15px;
      color: #000;
      height: 47px;
      border: 1px solid #ecf0f6;
      background: #f8f8f8;
      caret-color: $cursor;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #000 !important;
      }
    }
  }
}
.login-btn {
  margin-top: 30px;
  width: 100%;
}
.send_code {
  opacity: 1;
  color: #565454;
}
</style>
